from fastapi import APIRouter, Depends, Request, Form, HTTPException
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from typing import Optional
import json
from sqlalchemy.orm import Session
from database import get_db
from crud import get_landmarks, get_routes, get_landmark, get_route, create_landmark, update_landmark, delete_landmark, create_route, update_route, delete_route
from models import Landmark as LandmarkModel, Route as RouteModel
from datetime import datetime

router = APIRouter()

# 设置模板目录
templates = Jinja2Templates(directory="templates")

# 管理界面路由
@router.get("/admin", response_class=HTMLResponse)
async def admin_home(request: Request, db: Session = Depends(get_db)):
    """管理界面首页"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        return RedirectResponse(url="/login")

    # 获取地标和路径数据
    landmarks = get_landmarks(db)
    routes = get_routes(db)

    return templates.TemplateResponse("admin/index.html", {
        "request": request,
        "user": current_user,
        "landmarks": landmarks,
        "routes": routes
    })

@router.get("/admin/api-docs", response_class=HTMLResponse)
async def admin_api_docs(request: Request):
    """API文档页面"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        return RedirectResponse(url="/login")
    return templates.TemplateResponse("admin/api_docs.html", {"request": request, "user": current_user})

# 地标管理
@router.get("/admin/landmarks", response_class=HTMLResponse)
async def admin_landmarks(request: Request, db: Session = Depends(get_db)):
    """地标管理页面"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        return RedirectResponse(url="/login")

    landmarks = get_landmarks(db)
    return templates.TemplateResponse("admin/landmarks.html", {"request": request, "landmarks": landmarks, "user": current_user})

@router.get("/admin/landmarks/create", response_class=HTMLResponse)
async def admin_landmark_create(request: Request):
    """创建地标页面"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        return RedirectResponse(url="/login")

    return templates.TemplateResponse("admin/landmark_form.html", {"request": request, "landmark": None, "user": current_user})

@router.get("/admin/landmarks/{id}/edit", response_class=HTMLResponse)
async def admin_landmark_edit(request: Request, id: int, db: Session = Depends(get_db)):
    """编辑地标页面"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        return RedirectResponse(url="/login")

    landmark = get_landmark(db, landmark_id=id)
    if not landmark:
        raise HTTPException(status_code=404, detail="地标未找到")
    return templates.TemplateResponse("admin/landmark_form.html", {"request": request, "landmark": landmark, "user": current_user})

@router.post("/admin/landmarks/save")
async def admin_landmark_save(
    request: Request,
    id: Optional[int] = Form(None),
    name: str = Form(...),
    lat: float = Form(...),
    lng: float = Form(...),
    summary: str = Form(...),
    details: str = Form(...),
    media: Optional[str] = Form("[]"),
    time: Optional[str] = Form(None),
    db: Session = Depends(get_db)
):
    """保存地标"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        return RedirectResponse(url="/login")

    # 打印调试信息
    print(f"接收到的媒体参数: {media}")

    media_list = []
    try:
        if media and media.strip():
            media_list = json.loads(media)
            print(f"解析后的媒体列表: {media_list}")
    except json.JSONDecodeError as e:
        print(f"解析媒体列表失败: {e}")
        media_list = []

    # 处理时间参数
    time_obj = None
    if time:
        try:
            time_obj = datetime.fromisoformat(time.replace('T', ' '))
        except ValueError:
            # 如果解析失败，使用默认时间
            time_obj = datetime.now().replace(hour=12, minute=0, second=0, microsecond=0)

    if id:  # 更新
        landmark = update_landmark(
            db=db,
            landmark_id=int(id),
            name=name,
            lat=lat,
            lng=lng,
            summary=summary,
            details=details,
            media=media_list,
            time=time_obj
        )
        if not landmark:
            raise HTTPException(status_code=404, detail="地标未找到")
    else:  # 创建
        landmark = create_landmark(
            db=db,
            name=name,
            lat=lat,
            lng=lng,
            summary=summary,
            details=details,
            creator_id=current_user.id,
            media=media_list,
            time=time_obj
        )

    return RedirectResponse(url="/admin/landmarks", status_code=303)

@router.get("/admin/landmarks/{id}/delete")
async def admin_landmark_delete(request: Request, id: int, db: Session = Depends(get_db)):
    """删除地标"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        return RedirectResponse(url="/login")

    success = delete_landmark(db, landmark_id=int(id))
    if not success:
        raise HTTPException(status_code=404, detail="地标未找到")
    return RedirectResponse(url="/admin/landmarks", status_code=303)

# 路径管理
@router.get("/admin/routes", response_class=HTMLResponse)
async def admin_routes(request: Request, db: Session = Depends(get_db)):
    """路径管理页面"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        return RedirectResponse(url="/login")

    routes = get_routes(db)
    return templates.TemplateResponse("admin/routes.html", {"request": request, "routes": routes, "user": current_user})

@router.get("/admin/routes/create", response_class=HTMLResponse)
async def admin_route_create(request: Request, db: Session = Depends(get_db)):
    """创建路径页面"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        return RedirectResponse(url="/login")

    landmarks = get_landmarks(db)
    return templates.TemplateResponse("admin/route_form.html", {"request": request, "route": None, "landmarks": landmarks, "user": current_user})

@router.get("/admin/routes/{id}/edit", response_class=HTMLResponse)
async def admin_route_edit(request: Request, id: int, db: Session = Depends(get_db)):
    """编辑路径页面"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        return RedirectResponse(url="/login")

    route = get_route(db, route_id=int(id))
    if not route:
        raise HTTPException(status_code=404, detail="路径未找到")

    landmarks = get_landmarks(db)
    return templates.TemplateResponse("admin/route_form.html", {"request": request, "route": route, "landmarks": landmarks, "user": current_user})

@router.post("/admin/routes/save")
async def admin_route_save(
    request: Request,
    id: Optional[int] = Form(None),
    name: str = Form(...),
    landmarks: Optional[str] = Form(None),
    db: Session = Depends(get_db)
):
    """保存路径"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        return RedirectResponse(url="/login")

    landmark_ids = []
    if landmarks:
        landmark_ids = [int(x) for x in json.loads(landmarks)]

    if id:  # 更新
        route = update_route(
            db=db,
            route_id=int(id),
            name=name,
            landmark_ids=landmark_ids
        )
        if not route:
            raise HTTPException(status_code=404, detail="路径未找到")
    else:  # 创建
        route = create_route(
            db=db,
            name=name,
            creator_id=current_user.id,
            landmark_ids=landmark_ids
        )

    return RedirectResponse(url="/admin/routes", status_code=303)

@router.get("/admin/routes/{id}/delete")
async def admin_route_delete(request: Request, id: int, db: Session = Depends(get_db)):
    """删除路径"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        return RedirectResponse(url="/login")

    success = delete_route(db, route_id=int(id))
    if not success:
        raise HTTPException(status_code=404, detail="路径未找到")
    return RedirectResponse(url="/admin/routes", status_code=303)
